package com.frx.datastruct.chaptereleven;

/**
 * Created by xurenfeng on 2019/3/14.
 * 基于size的优化
 */
public class UnionFind3 implements UF{

    /** parent[i] 表示i 指向的父节点*/
    private int[] parent;
    /** sz[i] 表示以 i为根的集合中元素个数*/
    private int[] sz;

    public UnionFind3(int size){
        parent = new int[size];
        sz = new int[size];
        for (int i=0;i<size;i++){
            parent[i] = i;
            sz[i] = i;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    private int find(int p){

        if (p < 0 || p >= parent.length){
            throw new IllegalArgumentException(" p is out of bound !");
        }
        while (p != parent[p]){
            p = parent[p];
        }
        return p;
    }
    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {

        int pRoot = parent[p];
        int qRoot = parent[q];
        if (sz[p] > sz[q]){
            parent[qRoot] = pRoot;
            sz[p] += sz[q];
        } else {
            parent[pRoot] = qRoot;
            sz[q] += sz[p];
        }
    }
}
